package com.kaka.controller;

import com.kaka.bean.Admin;
import com.kaka.bean.Result;
import com.kaka.bean.Student;
import com.kaka.bean.Teacher;
import com.kaka.service.MainService;
import com.kaka.service.serviceimpl.MainServiceImpl;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

@WebServlet(name = "mainController", value = "/login")
public class MainController extends HttpServlet {
    private final MainService mainService = new MainServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/page/main.html").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String status = req.getParameter("status");
        HttpSession session = req.getSession();

        if ("1".equals(status)) {
            Admin admin = mainService.adminLogin(username, password);
            if (admin != null) {
                Result.success(req, resp, admin);
            } else {
                Result.error(req, resp);
            }
        } else if ("2".equals(status)) {
            Teacher teacher = mainService.teacherLogin(username, password);
            if (teacher != null) {
                session.setAttribute("teacher", teacher);
                Result.success(req, resp, teacher);
            } else {
                Result.error(req, resp);
            }
        } else if ("3".equals(status)) {
            Student student = mainService.studentLogin(username, password);
            if (student != null) {
                Result.success(req, resp, student);
            } else {
                Result.error(req, resp);
            }
        }
    }
}
